package com.kehutong.crm.message.service;

import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;
import com.kehutong.common.enums.MessageBusinessEnum;
import com.kehutong.common.enums.MessageBusinessStateEnum;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.crm.message.entity.MessageGlobalConfig;
import com.kehutong.crm.message.entity.MessageTemplateInner;

@WebService("/crm/message/inner/service")
public class MessageInnerService {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private MessageGlobalConfigService globalConfigService;

    public Object listPage(JSONObject jsonObject) {

        return Result.success(jdbcSession.findPage(MessageTemplateInner.class)
                                         .like(jsonObject, "name")
                                         .eq("deleted", false)
                                         .order("createTIme", "desc")
                                         .page(jsonObject)
                                         .exe());
    }

    public Object save(MessageTemplateInner inner) {
        if (checkDuplicateByType(inner.getId(), inner.getTemplateType())) {
            return Result.error(0, "模板类型已存在");
        }

        if (inner.getTemplateType().isCompleted()) {
            inner.setBusinessStateEnum(MessageBusinessStateEnum.MSG_SUCCESS);
        } else {
            inner.setBusinessStateEnum(MessageBusinessStateEnum.MSG_PRE_SUCCESS);
        }

        // sync global config
        resetGlobalConfig(inner.getId());
        syncGlobalConfig(inner.getBusinessType(), inner.getTemplateType(), inner.getId());

        jdbcSession.insert(inner);

        return Result.success();
    }

    public Object update(MessageTemplateInner inner) {
        if (checkDuplicateByType(inner.getId(), inner.getTemplateType())) {
            return Result.error(0, "模板类型已存在");
        }

        // sync global config
        resetGlobalConfig(inner.getId());
        syncGlobalConfig(inner.getBusinessType(), inner.getTemplateType(), inner.getId());

        jdbcSession.updateById(inner);

        return Result.success();
    }

    public Object delete(MessageTemplateInner inner) {
        inner.setDeleted(true);
        jdbcSession.updateById(inner);

        return Result.success();
    }

    public void init(String tagString, String title, String content, TemplateType templateType, MessageBusinessEnum businessEnum){
        MessageTemplateInner template = getMessageTemplateInner(templateType.getId());

        if (Objects.isNull(template)) {
            template = Pool.newInstance(MessageTemplateInner.class);
            template.setTagArray(tagString);
            template.setBusinessType(businessEnum);
            template.setTemplateType(templateType);
            template.setTitle(title);
            template.setContent(content);
            if (templateType.isCompleted()) {
                template.setBusinessStateEnum(MessageBusinessStateEnum.MSG_SUCCESS);
            } else {
                template.setBusinessStateEnum(MessageBusinessStateEnum.MSG_PRE_SUCCESS);
            }
            jdbcSession.insert(template);
        } else {
            template.setTagArray(tagString);
            template.setBusinessType(businessEnum);
            template.setTemplateType(templateType);
            template.setTitle(title);
            template.setContent(content);
            jdbcSession.updateById(template);
        }

        // sync global config
        resetGlobalConfig(template.getId());
        syncGlobalConfig(template.getBusinessType(), template.getTemplateType(), template.getId());
    }

    @ReqMapping("/getObj")
    public MessageTemplateInner getMessageTemplateInner(String templateType) {
        return jdbcSession.findOne(MessageTemplateInner.class)
                          .eq("templateType", templateType)
                          .eq("deleted", false)
                          .exe();
    }

    private void resetGlobalConfig(String id){
        JSONObject json = new JSONObject();
        json.put("innerTemplate", id);
        globalConfigService.listGlobalConfig(json).forEach(e -> {
            e.setInnerTemplate(null);
            jdbcSession.updateById(e);
        });
    }
    private void syncGlobalConfig(MessageBusinessEnum businessState, TemplateType templateType, String id){
        MessageGlobalConfig globalConfig = globalConfigService.getGlobalConfig(templateType.getId());
        if (Objects.isNull(globalConfig)){
            globalConfig = Pool.newInstance(MessageGlobalConfig.class);
            globalConfig.setInnerTemplate(id);
            globalConfig.setBusinessEnum(businessState);
            globalConfig.setTemplateEnum(templateType);
            globalConfigService.save(globalConfig);
        } else {
            globalConfig.setInnerTemplate(id);
            globalConfig.setBusinessEnum(businessState);
            globalConfig.setTemplateEnum(templateType);
            globalConfigService.update(globalConfig);
        }
    }

    private boolean checkDuplicateByType(String id, TemplateType templateType){
        MessageTemplateInner template = getMessageTemplateInner(templateType.getId());
        return Objects.nonNull(template) && !id.equals(template.getId());
    }

    public MessageTemplateInner getInner(String templateType){
        return jdbcSession.findOne(MessageTemplateInner.class)
                          .eq("templateType", templateType)
                          .eq("deleted", false)
                          .exe();
    }

    @ReqMapping("/get")
    public Object get(String id){
        return Pool.get(MessageTemplateInner.class, id);
    }
    
}
